﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net.Sockets;
namespace Etalk.Library
{
    //命名
     public enum CommandKey
    {
        CONN,//连接  CONN|旅客|旅客Guest|ObjectID|
        LOGIN,//代理商登录(连接) LOGIN|代理商|LoginName|Password
        JOIN,//加入
        GONE,//离开
        PRIV, //私聊 PRIV|OwnerID|ObjectID|MSG
        CHAT  //聊天 CHAT|MSG|
    }
    public  delegate void RemoveClientHandler(Client obj);
    
     public class Comm
    {
        public static event RemoveClientHandler RemoveClientEvent;
        #region 发送消息
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="socketObj"></param>
        /// <param name="content"></param>
        public static void SendDataToClient(Socket socketObj, string content)
        {
            try
            {
                content += "|";
                byte[] buffer = Encoding.UTF8.GetBytes(content.ToCharArray());
                buffer[buffer.Length - 1] = 0;
                socketObj.Send(buffer, buffer.Length, 0);
            }
            catch (SocketException e)
            {
                socketObj.Close();
            }
        }
        public static int SendDataToClient(Client clientObj, string msgData)
        {
            try
            {
                //message += "0";
                //byte[] buffer = System.Text.Encoding.UTF8.GetBytes(message.ToCharArray());
                //buffer[buffer.Length - 2] = 0;
                //cl.Sock.Send(buffer, buffer.Length, 0); 
                if (clientObj.Sock.Connected)
                {
                    msgData += "|";
                    byte[] buffer = Encoding.UTF8.GetBytes(msgData.ToCharArray());
                    buffer[buffer.Length - 1] = 0;

                    return clientObj.Sock.Send(buffer, buffer.Length, 0);
                }
                else
                {
                    return 0;
                }
                //Byte[] byteData = Encoding.UTF8.GetBytes(msgData);
                //clientObj.Sock.Send(byteData);
            }
            catch (SocketException se)
            {
                //LOG
                if (RemoveClientEvent != null)
                    RemoveClientEvent(clientObj);
                return 0;
                // RemoveClient(clientObj);
            }
            catch (Exception e)
            {
                return 0;
            }
           

        }

        #endregion
       
       
    }
}
